package com.itclass.auth.handler.authentication.support;

import cn.hutool.json.JSONUtil;
import com.itclass.auth.constant.AuthServerConstants;
import com.itclass.auth.constant.RedisCacheKeyConstants;
import com.itclass.auth.exception.GitHubAuthenticationServiceException;
import com.itclass.auth.pojo.db.Result;
import com.itclass.auth.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 认证失败处理器
 */
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private StringRedisTemplate stringRedisTemplate;
    public LoginAuthenticationFailureHandler(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        StringBuilder sb = new StringBuilder();

        Class<? extends AuthenticationException> exceptionClass = exception.getClass();
        if (LockedException.class.isAssignableFrom(exceptionClass)  ) {
            sb.append("用户账号已经锁定，请求联系管理员解除账号锁定！");
        }else if (DisabledException.class.isAssignableFrom(exceptionClass) ){
            sb.append("用户账号已经失效，请求联系管理员开启账号！");
        } else if (GitHubAuthenticationServiceException.class.isAssignableFrom(exceptionClass)) {
            sb.append("GitHub认证异常,请重试认证");
        } else {
            sb.append("用户名或密码错误");
            String username = request.getParameter("username");
            if (StringUtils.isNotEmpty(username)) {
                String failCount = stringRedisTemplate.opsForValue().get(RedisCacheKeyConstants.LOGIN_FAILURE + username);
                if (StringUtils.isNotEmpty(failCount)) {
                    Integer count = Integer.valueOf(failCount);
                    count = AuthServerConstants.LoginFailCount - count;
                    if (count <= 0) {
                        sb.append("，登录失败，登录失败次数已用完，该账号已锁定！");
                    } else {
                        sb.append("，登录失败，剩余登录失败次数：");
                        sb.append(count);
                    }
                }
            }

        }
        // 设置响应内容类型为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 设置响应字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        // 创建一个包含错误信息的 JSON 对象
        String json = JSONUtil.toJsonStr(Result.fail().message(sb.toString()));
        response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));

    }
}
